<template>
<!--  <div>-->
<!--    <el-menu-->
<!--        default-active="2"-->
<!--        class="el-menu-vertical-demo"-->
<!--        @open="handleOpen"-->
<!--        @close="handleClose"-->
<!--    >-->
<!--      <el-sub-menu index="1">-->
<!--        <template #title>-->
<!--          <el-icon><location /></el-icon>-->
<!--          <span>Navigator One</span>-->
<!--        </template>-->
<!--      </el-sub-menu>-->
<!--    </el-menu>-->
<!--  </div>-->
  <div class="bg">
    <Top></Top>
    <div class="entity-item">
      <div class="userInfo">
        <div class="userImage">
          <div>
<!--            <el-upload-->
<!--                class="avatar-uploader"-->
<!--                :http-request="uploadImage"-->

<!--                ref="uploadRef"-->
<!--                auto-upload:false-->
<!--                :on-exceed="handleExceed"-->
<!--                list-type="picture"-->
<!--                :on-change="imageChanged"-->
<!--                v-model="fileList"-->
<!--                limit="1"-->
<!--                multiple:false-->
<!--            >-->
<!--              <el-image-->
<!--                  :src="sysUser.imageUrl"-->
<!--                  style="width: auto; height: 35vh"-->
<!--                  :zoom-rate="1.2"-->
<!--                  lazy />-->

<!--            </el-upload>-->
            <el-image
                :src="sysUser.imageUrl"
                style="width: auto; height: 35vh"
                :zoom-rate="1.2"
                lazy />

          </div>
          <div>
            <input type="file" style="display: none" @change="changeImage" ref="avatar" v-show="false" />
            <el-button type="primary" size="large" @click="chooseImage">
              修改图片
            </el-button>
          </div>
        </div>

        <div class="otherInfo">
          <div class="infoItem">
            <el-text size="large" class="tripText">用户名</el-text>
            <el-input v-model="sysUser.username" size="large" disabled="false"></el-input>
          </div>

          <div class="infoItem">
            <el-text size="large" class="tripText">昵称</el-text>
            <el-input v-model="sysUser.nickname" size="large" ></el-input>
          </div>

          <div class="infoItem">
            <el-text size="large" class="tripText">所在地区</el-text>
            <el-tree-select size="large" v-model="sysUser.divisionCode" :data="divisionList" :props="{label: 'divisionName', value: 'divisionCode'}" :render-after-expand="false" />
          </div>
          <div class="infoItem">
            <el-text size="large" class="tripText">简介</el-text>
            <el-input v-model="sysUser.introduction" size="large" type="textarea"></el-input>
          </div>
          <div class="infoItem">
            <el-button type="primary" size="large" @click="changeUserInfo">
              提交修改
            </el-button>
            <el-button type="primary" size="large" @click="dialogFormVisible = true">
              修改密码
            </el-button>
          </div>

          <el-dialog title="修改密码" v-model="dialogFormVisible">
            <div class="otherInfo">
              <div class="infoItem">
                <el-text size="large" class="tripText">旧密码</el-text>
                <el-input v-model="oldPassword" size="large" type="password"></el-input>
              </div>
              <div class="infoItem">
                <el-text size="large" class="tripText">新密码</el-text>
                <el-input v-model="newPassword" size="large" type="password"></el-input>
              </div>
              <div class="infoItem">
                <el-text size="large" class="tripText">确认密码</el-text>
                <el-input v-model="newPasswordConfirm" size="large" type="password"></el-input>
              </div>
              <div class="infoItem">
                <el-button type="primary" size="large" @click="changePassword">
                  确认修改
                </el-button>
                <el-button type="primary" size="large" @click="dialogFormVisible = false">
                  放弃修改
                </el-button>
              </div>
            </div>
          </el-dialog>

        </div>

      </div>

    </div>
  </div>
  <el-affix position="bottom" :offset="20">
    <el-button type="primary" size="large" @click="toAdmin" v-if="userIsAdmin" circle>管理</el-button>
  </el-affix>

</template>

<script>
import Top from "@/components/Top";
import utils from "@/js/util/utils"
// import { UploadProps } from 'element-plus'
import {getUserInfo} from "@/manager/UserManager"
import {ref} from "vue";
import axios from "@/settings/axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import {ADMIN_ROLE_NAME_EN} from "@/settings/sysMapping";
import * as sysMapping from "@/settings/sysMapping";

const uploadRef = ref();

export default {
  name: "UserInfo",
  components: {Top},
  data() {
    return {
      sysUser: {},
      fileList: [],
      divisionList: [],
      password: [],
      dialogFormVisible: false,
      oldPassword: "",
      newPassword: "",
      newPasswordConfirm: "",
      userIsAdmin: false,
      newImageUrl: "",

    }
  },
  async mounted() {

    this.sysUser = await getUserInfo();
    let divisionResult = await axios.get("/sys_division/get_division_tree_by_level");
    this.divisionList = divisionResult;
    this.userIsAdmin = this.sysUser.roleNameEnList.includes(ADMIN_ROLE_NAME_EN);

  },
  methods: {
    async changeUserInfo() {
      let userInfo = await getUserInfo();
      let sysUserParams = {
        "id": userInfo.userId,
        "nickname": this.sysUser.nickname,
        "divisionCode": this.sysUser.divisionCode,
        "divisionId": this.sysUser.divisionCode,
        "introduction": this.sysUser.introduction,
        "imageUrl": this.sysUser.imageUrl,
      }
      let changeUserInfoVO = await axios.post("/SysUser/update_user_info", sysUserParams);
      // 删除缓存中的用户信息，以实时同步
      localStorage.removeItem(sysMapping.USER_INFO);
      if (changeUserInfoVO.successed === "0") {
        ElMessage({
          showClose: true,
          message: changeUserInfoVO.message,
          type: 'error',
          center: true,
        });
        return false;
      }
      else if (changeUserInfoVO.successed === "1") {
        ElMessage({
          showClose: true,
          message: changeUserInfoVO.message,
          type: 'success',
          center: true,
        });
        // 刷新页面
        location.reload();
      }
    },
    async chooseImage() {
      // console.log(uploadRef.value);

      this.$refs.avatar.click();
      // alert(this.$refs.avatar)

    },
    // eslint-disable-next-line no-unused-vars
    async changeImage(e) {

      const formData = new FormData();
      formData.set('file', e.target.files[0]);
      console.log(formData);
      let newImageUrl = await axios.postImage("/image/uploadImage", formData);
      this.newImageUrl = newImageUrl;
      this.sysUser.imageUrl = newImageUrl;

      // alert(newImageUrl);
    },
    async handleExceed(files) {
      // console.log(uploadRef)
      // console.log(uploadRef.value)
      console.log(files);
      uploadRef.value = files[0];
      //
      // uploadRef.value.clearFiles();
      if (files.length > 0) {
        this.fileList = await [files[files.length - 1]]
      }

    },
    async imageChanged(uploadFile, uploadFiles) {
      uploadFile = await uploadFile;
      uploadFiles = await uploadFiles;
      console.log(uploadFile);
      console.log(uploadFiles);
      console.log(uploadFiles.length);
      console.log(this.$refs.uploadRef)
      console.log(this.fileList);
      if (uploadFiles.length > 0) {
        this.fileList = await [uploadFiles[uploadFiles.length - 1]]
      }
    },
    async changePassword() {
      if (utils.isEmptyStr(this.oldPassword) ) {
        ElMessage({
          showClose: true,
          message: "旧密码未填写",
          type: 'error',
          center: true,
        });
        return false;
      }

      if (utils.isEmptyStr(this.newPassword) ) {
        ElMessage({
          showClose: true,
          message: "新密码未填写",
          type: 'error',
          center: true,
        });
        return false;
      }

      if (utils.isEmptyStr(this.newPasswordConfirm) ) {
        ElMessage({
          showClose: true,
          message: "新密码验证未填写",
          type: 'error',
          center: true,
        });
        return false;
      }

      if (this.newPassword != this.newPasswordConfirm ) {
        ElMessage({
          showClose: true,
          message: "两次密码输入不一致",
          type: 'error',
          center: true,
        });
        return false;
      }

      let checkParams = {
        "password": this.oldPassword
      };

      let oldPasswordIsTrue = await axios.post("/SysUser/check_user_password", checkParams);

      if (oldPasswordIsTrue === "0") {
        ElMessage({
          showClose: true,
          message: "旧密码错误",
          type: 'error',
          center: true,
        });
        return false;
      }

      let updatePasswordParams = {
        "newPassword": this.newPassword
      };
      let changePasswordData = await axios.post("/SysUser/update_password", updatePasswordParams);
      console.log(changePasswordData);

      if (changePasswordData.successed === "0") {
        ElMessage({
          showClose: true,
          message: "修改密码请求错误",
          type: 'error',
          center: true,
        });
        return false;
      }
      else if (changePasswordData.successed === "1") {
        ElMessage({
          showClose: true,
          message: "修改密码成功",
          type: 'success',
          center: true,
        });
        // 关掉弹窗
        this.dialogFormVisible = false;
      }

    },
    toAdmin() {
      router.push("/admin/question")
    },
  },
  computed: {

  },

};
</script>

<style scoped>

body {
  background-color: #f0f0f0; /* 这里可以设置你想要的颜色 */

}

.bg{
  background-color: rgb(255, 255, 255);

}

.entity-item {
  padding: 40px;

}

.userInfo {
  color: #f0f0f0;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.userImage {
  display: flex;
  flex-direction: column;  /* 上下排列 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 20px;
}

.userImage > div {
  margin-bottom: 20px;
  margin-left: 20px;
  margin-right: 20px;
}

.otherInfo {
  display: flex;
  flex-direction: column;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */

}

.infoItem {
  display: flex;
  flex-direction: row;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 5px;
}

.tripText {
  display: flex;
  width: 10vw;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

question-info {
  display: flex;
}

</style>
